package org.leon.org.leon.service;

import org.leon.dao.AuthCodeRepository;
import org.leon.dao.TokenRepository;
import org.leon.entity.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class LoginTokenServiceImpl implements LoginTokenService {

    private TokenRepository tokenRepository;
    private AuthCodeRepository authCodeRepository;

    @Autowired
    public LoginTokenServiceImpl(TokenRepository tokenRepository, AuthCodeRepository authCodeRepository) {
        this.tokenRepository = tokenRepository;
        this.authCodeRepository = authCodeRepository;
    }

    /**
     * 注册
     */
    @Override
    public String register(String email, String password) {
        // 当前注册逻辑, 直接向 token 表中插入一条记录即可
        Token tokenEntity = checkEmailExisted(email);
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        if (tokenEntity == null) {
            insertIntoToken(email, token);
        } else {
            tokenEntity.setToken(token);
            updateToken(tokenEntity);
        }
        return token;
    }

    /**
     * 判断指定邮箱是否已经注册
     */
    @Override
    public Token checkEmailExisted(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example<Token> example = Example.of(token);
        List<Token> results = tokenRepository.findAll(example);
        if (results.size() > 0) {
            return results.get(0);
        }
        return null;
    }

    /**
     * 检查 邮箱/密码 是否匹配, 如果匹配则返回一个 UUID
     */
    @Override
    public Optional<String> checkEmailAndPassword(String email, String password) {
        // 验证账户/密码, 这里直接检查是否有注册邮箱即可
        Token tokenEntity = checkEmailExisted(email);
        if (tokenEntity == null) {
            return Optional.empty();
        }

        UUID uuid = UUID.randomUUID();
        String t = uuid.toString();
        tokenEntity.setToken(t);
        updateToken(tokenEntity);

        return Optional.of(t);
    }

    /**
     * 检查是否是有效 token, 返回对应的邮箱地址
     */
    @Override
    public String checkToken(String token) {
        Token t = new Token();
        t.setToken(token);
        Example<Token> example = Example.of(t);
        List<Token> results = tokenRepository.findAll(example);
        if (results.size() > 0) {
            return results.get(0).getEmail();
        }
        return "";
    }

    /**
     * 向 token 表添加一条记录
     */
    private void insertIntoToken(String email, String token){
        Token tokenRecord = new Token();
        tokenRecord.setEmail(email);
        if (token != null) {
            tokenRecord.setToken(token);
        }

        tokenRepository.save(tokenRecord);
    }

    private void updateToken(Token tokenEntity) {
        tokenRepository.save(tokenEntity);
    }

}
